<template>
	<div ref="largeScreenRef" class="main__wrapper">
		<div class="main">
			<div class="large_screen">
				<div class="large_header">
					<div class="header_time">
						<span>{{ currentTime.time }}</span>
						<span>{{ currentTime.date }}</span>
						<span>{{ currentTime.week }}</span>
						<span>衢州市江山市</span>
					</div>
					<img class="header_title" src="./image/icon_header_title.png" />
					<div class="header_manager" @click="handleManager">
						<img src="./image/icon_manager.png" alt />
						<span>管理后台</span>
					</div>
					<img
						v-if="!isFullScreen"
						class="header_full"
						src="./image/icon_full_b.png"
						@click="changeFullScreen"
					/>
					<img v-else class="header_full" src="./image/icon_full_p.png" @click="changeFullScreen" />
				</div>
				<div v-show="activeTableIndex == 4" class="plant_container">
					<plantView v-if="plantImgUrl" :img-url="plantImgUrl"></plantView>
				</div>
				<div v-show="activeTableIndex != 4" class="map_container" id="mapContainer"></div>
				<img class="large_bottom" src="./image/icon_bottom_bg.png" alt />
				<div class="large_bottom_table">
					<div
						class="table_item"
						v-for="(item, index) in tableArray"
						:key="index"
						@click="handleTableItem(item)"
					>
						<img v-if="activeTableIndex == item.id" :src="item.activeIcon" alt />
						<img v-else :src="item.icon" alt />
						<div class="table_item_label">
							<img v-if="activeTableIndex == item.id" :src="item.activeLabel" alt />
							<img v-else :src="item.label" alt />
						</div>
					</div>
				</div>
				<div class="large_center_info" v-if="activeTableIndex == 1">
					<div class="info_item" v-for="(item, index) in infoDataArray" :key="index">
						<div class="info_item_value">
							<span style="line-height: 1">{{ item.value }}</span>
							<span style="font-size: 18px">{{ item.unit }}</span>
						</div>
						<div class="info_item_label">{{ item.label }}</div>
					</div>
				</div>
				<div
					class="large_center_plant"
					v-if="activeTableIndex == 4"
				>植被指数在-1至1之间，值为1表示植被生长状况良好，而值为-1表示无植被覆盖。</div>
				<div class="large_box_left">
					<!-- 经营主体 -->
					<!-- <bussinessView v-if="activeTableIndex == 2" @clickLocation="handleBussinessLocation" @clickItem="handleBussinessItem"></bussinessView> -->
					<baseLeft
						:leftCode="leftCode"
						@toMarkerLocation="toMarkerLocation"
						v-if="activeTableIndex == 1"
					></baseLeft>
					<!-- 视频监控 -->
					<videoView v-else-if="activeTableIndex == 3"></videoView>
					<!-- 植被指数 -->
					<div class="uav_item" v-else-if="activeTableIndex == 4">
						<el-select
							v-model="currentPlantValue"
							placeholder="请选择日期"
							popper-class="selectTimeName"
							:teleported="false"
							style="min-width: 120px;"
							@change="handleUavTimeChange"
						>
							<el-option v-for="(item,index) in plantArray" :key="index" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</div>
				</div>
				<div class="large_box_right">
					<div class="tool_bar" v-if="[2, 3].includes(activeTableIndex)">
						<div class="layer_item" @click="handleLayerItem('base')">
							<div class="bk yellow">
								<div v-if="layerForm.base" class="active_yellow"></div>
							</div>
							<div>基地边界</div>
						</div>
						<!-- <div class="layer_item" @click="handleLayerItem('bussiness')" v-if="activeTableIndex == 3">
							<div class="bk green">
								<div v-if="layerForm.bussiness" class="active_green"></div>
							</div>
							<div>经营主体边界</div>
						</div> -->
						<div class="uav_item">
							<el-select
								v-model="mapOption.uavLayerType"
								placeholder="请选择图层"
								popper-class="selectTimeName"
								style="min-width: 120px"
								:teleported="false"
								@change="handleUavLayerChange"
							>
								<el-option v-for="item in mapOption.layerTypeList" :key="item" :label="item" :value="item"></el-option>
							</el-select>
							<el-select
								v-show="mapOption.isShowUavTime"
								v-model="mapOption.uavTime"
								placeholder="请选择月份"
								popper-class="selectTimeName"
								:teleported="false"
								style="min-width: 120px; margin-left: 10px"
								@change="handleUavTimeChange"
							>
								<el-option v-for="item in mapOption.uavTimes" :key="item" :label="item" :value="item"></el-option>
							</el-select>
						</div>
					</div>
					<bussinessDetailView v-show="activeTableIndex == 2" ref="bussDetailRef"></bussinessDetailView>
					<baseRight
						:rightCode="rightCode"
						@toMarkerLocation="toMarkerLocation"
						v-if="activeTableIndex == 1"
					></baseRight>
					<div v-if="activeTableIndex == 3" style="height:200px;width:1px;"></div>
				</div>
				<div class="plant_color" v-if="activeTableIndex == 4">
					<div class="title">植被指数</div>
					<div class="color">
						<img src="./image/icon_plant_color.png" alt />
						<div class="value">
							<div>1</div>
							<div>0.5</div>
							<div>0</div>
							<div>-0.5</div>
							<div>-1</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<videoPlayDialog
			v-if="isShowVideoDialog"
			ref="videoViewRef"
			:is-show-dialog="isShowVideoDialog"
			:row="currVideoItem"
			:video-list="videoList"
			:device-serial="deviceSerial"
			@clickClose="handleVideoDialogClose"
		></videoPlayDialog>
	</div>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue';
import { useFullScreen } from '/@/hooks/fullScreen';
import { useBodySize } from '/@/hooks/bodySize';
import { useMapMethod, BasicMapProps } from '/@/hooks/map';
import { getLotdeviceregisterList } from '/@/api/largeScreen/baseView';
import * as L from 'leaflet';
import { NextLoading } from '/@/utils/loading';
import { geoData } from './data.js';
import { Session } from '/@/utils/storage';

// const bussinessView = defineAsyncComponent(() => import('./template/business/index.vue'));
const bussinessDetailView = defineAsyncComponent(() => import('./template/business/detail.vue'));
const videoView = defineAsyncComponent(() => import('./template/video/index.vue'));
const videoPlayDialog = defineAsyncComponent(() => import('./template/video/playDialog.vue'));
const baseLeft = defineAsyncComponent(() => import('./template/baseView/left.vue'));
const baseRight = defineAsyncComponent(() => import('./template/baseView/right.vue'));
const plantView = defineAsyncComponent(() => import('./template/plant/p-image.vue'))

const largeScreenRef = ref();
const bussDetailRef = ref();

const isFullScreen = ref(false);
const timer = ref();
const mediaList = ref([]);
const currentTime = reactive({
	time: '',
	date: '',
	week: '',
});
//是否显示视频监控播放器
const isShowVideoDialog = ref(false);
// 经营主体
const businessInfo = {
	name: '江山市富美新塘集体经济发展有限公司',
	lat: 28.585267,
	lng: 118.4748673,
};

const plantArray = reactive([
	{
		label:'2025-08',
		value:'2025-08',
		imgUrl:new URL('./image/icon_plant.png',import.meta.url)
	}
])
const currentPlantValue = ref('2025-08')

const plantImgUrl = computed(() =>{
	let item = plantArray.find((o) => o.value == currentPlantValue.value)
	return item ? item.imgUrl : ''
})

const tableArray = reactive([
	{
		id: 1,
		label: new URL('./image/icon_table_base_label_b.png', import.meta.url),
		activeLabel: new URL('./image/icon_table_base_label_p.png', import.meta.url),
		icon: new URL('./image/icon_table_base_img_b.png', import.meta.url),
		activeIcon: new URL('./image/icon_table_base_img_p.png', import.meta.url),
	},
	{
		id: 2,
		label: new URL('./image/icon_table_buss_label_b.png', import.meta.url),
		activeLabel: new URL('./image/icon_table_buss_label_p.png', import.meta.url),
		icon: new URL('./image/icon_table_buss_img_b.png', import.meta.url),
		activeIcon: new URL('./image/icon_table_buss_img_p.png', import.meta.url),
	},
	{
		id: 3,
		label: new URL('./image/icon_table_video_label_b.png', import.meta.url),
		activeLabel: new URL('./image/icon_table_video_label_p.png', import.meta.url),
		icon: new URL('./image/icon_table_video_img_b.png', import.meta.url),
		activeIcon: new URL('./image/icon_table_video_img_p.png', import.meta.url),
	},
	{
		id: 4,
		label: new URL('./image/icon_table_plant_label_b.png', import.meta.url),
		activeLabel: new URL('./image/icon_table_plant_label_p.png', import.meta.url),
		icon: new URL('./image/icon_table_plant_img_b.png', import.meta.url),
		activeIcon: new URL('./image/icon_table_plant_img_p.png', import.meta.url),
	},
]);
const activeTableIndex = ref(1);
const handleTableItem = async (row: any) => {
	clearMarkerLayer();
	activeTableIndex.value = row.id;
	if (activeTableIndex.value == 1) {
		getMediaList();
	} else if (activeTableIndex.value == 2) {
		await nextTick()
		addMarkerToMap(Object.assign(businessInfo, { title: businessInfo.name }));
		mapOption.map.setView([businessInfo.lat, businessInfo.lng]);
		bussDetailRef.value.getDetailInfo(businessInfo);
	}else if(activeTableIndex.value == 3){
		await getVideoList()
	}
	if ([2, 3].includes(activeTableIndex.value)) {
		layerForm['base'] && showRegionBound();
		mapOption.isShowUavTime && mapOption.uavTime && handleUavTimeChange();
	}
};
const leftCode = ref([]);
const rightCode = ref([]);
const infoDataArray = reactive([
	{
		label: '基地总面积',
		value: 600,
		unit: '亩',
	},
	{
		label: '经营主体',
		value: 1,
		unit: '家',
	},
	{
		label: '茶叶年产值',
		value: 300,
		unit: '万',
	},
]);

// 图层显示
const layerForm = reactive({
	base: false,
	bussiness: false,
});
const handleLayerItem = (e: String) => {
	layerForm[e] = !layerForm[e];

	if (e == 'base') {
		layerForm[e] ? showRegionBound() : clearRegionBound();
	}
};

const showRegionBound = () => {
	var regionStyle = {
		color: '#ffe63f',
		weight: 2,
		opacity: 1,
		fillColor: '#ffe63f',
		fillOpacity: 0,
	};
	if (!mapOption.regionLinesLayer) {
		mapOption.regionLinesLayer = new L.LayerGroup();
		mapOption.regionLinesLayer.addTo(mapOption.map);
	}
	var markerArray: any[] = [];
	var geo_l = L.geoJson(geoData, {
		onEachFeature: function (feature: any, layer: any) {
			if (feature.geometry.type === 'MultiPolygon' || feature.geometry.type === 'Polygon') {
				layer.setStyle(regionStyle);
				var center = {
					lat: feature.properties.latitude,
					lng: feature.properties.longitude,
				};
				var content = `<div style='color:#ffffff;word-break:keep-all;padding:0 5px;margin-left: -16px;font-size:16px;'>${feature.properties.name}</div>`;
				var icon_div = L.divIcon({
					html: content,
					className: 'town_name',
				});
				let marker = L.marker(center, {
					icon: icon_div,
					clickable: false,
					draggable: false,
				});
				markerArray.push(marker);
			}
		},
	}).addTo(mapOption.map);
	mapOption.regionLinesLayer.addLayer(geo_l);
	let markerGroup = L.layerGroup(markerArray);
	mapOption.map.addLayer(markerGroup);
	(mapOption.regionNameMarkers || []).push(markerGroup);
	mapOption.map.fitBounds(geo_l.getBounds());
};

const clearRegionBound = () => {
	mapOption.regionLinesLayer && mapOption.regionLinesLayer.clearLayers();
	//清除文字
	if ((mapOption.regionNameMarkers || [])[0]) {
		mapOption.map.removeLayer((mapOption.regionNameMarkers || [])[0]);
		(mapOption.regionNameMarkers || []).pop();
	}
};

const toMarkerLocation = (name: any) => {
	mediaList.value.map((item: any) => {
		if (item.name == name) {
			mapOption.map.setView([item.latitude, item.longitude], 16);
		}
	});
};

//获取时间
const getCurrentTime = () => {
	let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'] as Array;
	timer.value = setInterval(() => {
		let nowTime = new Date();
		let year = nowTime.getFullYear();
		let month = nowTime.getMonth() + 1;
		let day = nowTime.getDate();
		currentTime.week = weeks[nowTime.getDay()];
		currentTime.time = nowTime.toLocaleTimeString();
		currentTime.date = `${year}年${month}月${day}日`;
	}, 1000);
};
//全屏
useFullScreen(largeScreenRef, isFullScreen);
//切换全屏
const changeFullScreen = () => {
	isFullScreen.value = !isFullScreen.value;
};
//自适应
const { initBodySize } = useBodySize(largeScreenRef);
//地图
const mapOption: BasicMapProps = reactive<BasicMapProps>({
	isShowRegionLayer: false,
	uavLayerType: '卫星影像',
	uavTime: '',
	map: null,
	isClickMap: false,
	markerLayer: null,
	regionNameMarkers: [],
	regionLinesLayer: null,
});
const { initMap, getUavTimeList, handleUavTimeChange, handleUavLayerChange, removeMap,  setViewForMap, removeUavLayers } = useMapMethod(mapOption);

/**
 * 添加marker
 * @param row
 */
const addMarkerToMap = (row: any) => {
	let lat = row.lat || 0,
		lng = row.lng || 0,
		title = row.title;
	if (lat == 0 || lng == 0) return;
	if (!mapOption.markerLayer) {
		mapOption.markerLayer = new L.LayerGroup();
		mapOption.markerLayer.addTo(mapOption.map);
	}
	let marker_tea_1 = new URL('./image/icon_marker_tea_1.png', import.meta.url);
	var content = `<div class="marker_box"><img src="${marker_tea_1}" /><div class="marker_box_label"><div class="point"></div><div>${title}</div></div></div>`;
	var icon_div = L.divIcon({
		html: content,
		className: 'tea_name',
		iconAnchor: [14, 85],
	});
	let marker = L.marker([lat, lng], {
		icon: icon_div,
		info: row,
	});
	marker.on('click',(e:any) =>{
		if(activeTableIndex.value == 2){
			bussDetailRef.value.getDetailInfo(businessInfo);
		}
	})
	mapOption.markerLayer.addLayer(marker);
};
//当前监控播放器
const currVideoItem = ref();

/**
 * 添加监控marker
 * @param row
 */
const addVideoMarkerToMap = (row: any) => {
	if (row.latitude == 0 || row.longitude == 0) return;
	if (!mapOption.markerLayer) {
		mapOption.markerLayer = new L.LayerGroup();
		mapOption.markerLayer.addTo(mapOption.map);
	}
	var icon = L.icon({
		iconUrl: new URL('./image/icon_marker_video.png', import.meta.url),
		iconSize: [50, 60],
		iconAnchor: [25, 45],
	});
	let marker = L.marker([row.latitude, row.longitude], {
		icon: icon,
		info: row,
	});
	marker.on('click', async (e: any) => {
		currVideoItem.value = e.target.options.info;
		isShowVideoDialog.value = true;
	});
	mapOption.markerLayer.addLayer(marker);
};

/**
 * 清除marker
 */
const clearMarkerLayer = () => {
	mapOption.regionLinesLayer && mapOption.regionLinesLayer.clearLayers();
	mapOption.markerLayer && mapOption.markerLayer.clearLayers();
	mapOption.regionNameMarkers?.length && mapOption.map.removeLayer(mapOption.regionNameMarkers[0]);
	mapOption.regionNameMarkers?.length && mapOption.regionNameMarkers.pop();
	removeUavLayers();
};
/**
 * 关闭视频播放弹窗
 */
const handleVideoDialogClose = () => {
	isShowVideoDialog.value = false;
};

// 获取设备列表
const getMediaList = () => {
	getLotdeviceregisterList({
		typeCodeList: '02,05,06,26',
		appId: 'dfcy',
		status: '1',
	}).then((res: any) => {
		let list = res.data || [];
		mediaList.value = list;
		leftCode.value = [mediaList.value[0].code];
		rightCode.value = mediaList.value
			.map((item: any) => {
				return item.code;
			})
			.filter((item, index) => {
				return index > 0;
			});
		list.map((item: any) => {
			let obj = {
				lat: item.latitude,
				lng: item.longitude,
				title: item.name,
			};
			addMarkerToMap(obj);
		});
	});
};

const videoList = ref()
const deviceSerial = ref()
/**
 * 获取监控设备列表
 */
const getVideoList = async () =>{
	const data = await getLotdeviceregisterList({ typeCodeList: '01,25', appId: 'dfcy' });
    if(data && data.code == 0 ){
		let item = data.data.find((o) => o.typeCode == '25')
		deviceSerial.value = item ? item.code :''
		videoList.value = data.data.filter((o) => o.exData1Id).map((o) =>{
			o['id'] = o.code
			return o
		}) || []
    }
	if(videoList.value.length > 0){
		let latlngs: any[][] = []
		videoList.value.forEach((item:any) =>{
			addVideoMarkerToMap(item)
			latlngs.push([item.latitude,item.longitude])
		})
		setViewForMap(latlngs)
	}
}
//管理后台
const handleManager = () =>{
	window.open('https://nyzbwlw.com/platform/#/login')
}

onMounted(async () => {
	console.log();
	let regionCode = Session.get('regionCode');
	NextLoading.done();
	await nextTick();
	getCurrentTime();
	initBodySize();
	getMediaList();
	await initMap('mapContainer');
	getUavTimeList(regionCode);
});

onBeforeUnmount(() => {
	if (timer.value) {
		clearInterval(timer.value);
		timer.value = null;
	}
	removeMap();
});
</script>
<style lang='less' scoped>
@import url('./index.less');

.main__wrapper {
	width: 100%;
	height: 100%;
	.main {
		position: absolute;
		top: 0;
		width: 1920px;
		height: 100%;
		background-size: 100% 100%;
		transform-origin: left top;
	}
}
.large_screen {
	width: 100%;
	height: 100%;
	position: relative;
	background-color: #121719;
	flex: 1;
	.large_header {
		width: 100%;
		height: 72px;
		display: flex;
		align-items: center;
		justify-content: center;
		background: url('./image/icon_header_bg.png') no-repeat;
		background-size: 100% 100%;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 500;
		.header_time {
			color: #c9ffff;
			font-size: 18px;
			position: absolute;
			left: 32px;
			span {
				margin-right: 18px;
				&:last-child {
					margin-right: 0;
				}
			}
		}
		.header_title {
			width: 386px;
			height: 30px;
		}
		.header_manager {
			position: absolute;
			right: 136px;
			display: flex;
			align-items: center;
			color: #c9ffff;
			font-size: 16px;
			font-weight: bold;
			cursor: pointer;
			img {
				width: 14px;
				height: 14px;
				margin-right: 8px;
			}
		}
		.header_full {
			position: absolute;
			right: 48px;
			width: 24px;
			height: 24px;
			cursor: pointer;
		}
	}
	.map_container {
		width: 100%;
		height: 100%;
		position: relative;
		z-index: 300;
	}
	.plant_container{
		width: 100%;
		height: 100%;
		position: relative;
		z-index: 310;
	}
	.large_bottom {
		width: 100%;
		height: 64px;
		position: absolute;
		left: 0;
		bottom: 0;
		z-index: 700;
	}
	.large_bottom_table {
		position: absolute;
		bottom: 20px;
		z-index: 1000;
		left: calc(50% - 205px);
		display: flex;
		align-items: center;
		.table_item {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-right: 40px;
			cursor: pointer;
			&:last-child {
				margin-right: 0;
			}
			img {
				width: 48px;
				height: 48px;
				margin-bottom: 8px;
			}
			&_label {
				img {
					width: 72px;
					height: 16px;
					margin: 0;
				}
			}
		}
	}
}
.large_center_info {
	position: absolute;
	top: 88px;
	left: calc(50% - 210px);
	z-index: 1000;
	width: 420px;
	height: 58px;
	display: flex;
	align-items: flex-start;
	justify-content: center;
	background: url('./image/icon_center_info_bg.png') no-repeat;
	background-size: 100% 100%;
	.info_item {
		display: flex;
		align-items: center;
		flex-direction: column;
		margin-right: 52px;
		&:last-child {
			margin-right: 0;
		}
		&_value {
			height: 20px;
			display: flex;
			align-items: flex-end;
			color: #3fffff;
			font-weight: bold;
			font-size: 28px;
			margin-bottom: 6px;
		}
		&_label {
			font-size: 14px;
			font-weight: bold;
			color: #ffffff;
		}
	}
}
.large_center_plant {
	position: absolute;
	top: 88px;
	left: calc(50% - 279px);
	z-index: 1000;
	width: 558px;
	height: 34px;
	text-align: center;
	line-height: 34px;
	background: url('./image/icon_plant_bg.png') no-repeat;
	background-size: 100% 100%;
	color: #c9ffff;
	font-size: 14px;
}
.large_box_left {
	position: absolute;
	left: 16px;
	top: 88px;
	z-index: 800;
	max-height: calc(100% - 132px);
	overflow-y: auto;
}
.large_box_right {
	position: absolute;
	right: 16px;
	top: 88px;
	z-index: 800;
	max-height: calc(100% - 132px);
	overflow-y: auto;
}
.tool_bar {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	.layer_item {
		display: flex;
		align-items: center;
		margin-right: 8px;
		height: 30px;
		padding: 0 14px;
		background: rgba(0, 22, 51, 0.6);
		border: 1px solid #0f7196;
		color: #ffffff;
		font-size: 14px;
		cursor: pointer;
		.bk {
			width: 12px;
			height: 12px;
			border-radius: 2px;
			margin-right: 4px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.yellow {
			border: 1px solid #ffe63f;
			.active_yellow {
				background-color: #ffe63f;
				width: 6px;
				height: 6px;
			}
		}

		.green {
			border: 1px solid #02d48e;
			.active_green {
				background-color: #02d48e;
				width: 6px;
				height: 6px;
			}
		}
	}
}
.plant_color {
	position: absolute;
	left: 16px;
	bottom: 20px;
	z-index: 1000;
	width: 96px;
	height: 226px;
	background-color: #00000050;
	border-radius: 4px;
	padding: 16px;
	box-sizing: border-box;
	.title {
		color: #ffffff;
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 18px;
	}
	.color {
		display: flex;
		align-items: center;
		img {
			width: 12px;
			height: 148px;
			margin-right: 12px;
		}
		.value {
			color: #ffffff;
			font-size: 16px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			div {
				margin-bottom: 12px;
				line-height: 1;
				&:last-child {
					margin-bottom: 0;
				}
			}
		}
	}
}
</style>